const path = require("path");
const inquirer = require("inquirer");
const fs = require("fs");
const iftsp = require("inquirer-file-tree-selection-prompt");
const execa = require("execa");
inquirer.registerPrompt("file-tree-selection", iftsp);
module.exports = (name) => {
  let promptArr = [
    {
      type: "input",
      message: "请输入新专题目录名称：",
      name: "projectName",
      validate(val) {
        let reg = /^[a-zA-Z][\w\-]*$/;
        if (reg.test(val)) {
          return true;
        } else {
          return `1.以大小写字母开头；\n   2.包含字母数字下划线。`;
        }
      },
    },
    {
      type: "file-tree-selection",
      message: "请选择专题集合目录：",
      name: "programDir",
      // 只显示目录
      onlyShowDir: true,
      validate(val) {
        let dirName = val.split(path.sep).pop();
        return !/^\./.test(dirName);
      },
    },
  ];
  name && promptArr.shift();
  inquirer.prompt(promptArr).then((res) => {
    let projectName = name || res.projectName;
    const reg = /\${insertVal}/g;
    let vueComponent = fs.readFileSync(
      path.resolve(__dirname, "../components/template-vue.xml"),
      { encoding: "utf-8" }
    );
    vueComponent = vueComponent.replace(reg, projectName);
    let jsComponent = fs.readFileSync(
      path.resolve(__dirname, "../components/template-js.xml"),
      { encoding: "utf-8" }
    );
    jsComponent = jsComponent.replace(reg, projectName);
    let cssComponent = fs.readFileSync(
      path.resolve(__dirname, "../components/template-css.xml"),
      { encoding: "utf-8" }
    );
    let jsFile = fs.readFileSync(
      path.resolve(__dirname, "../components/template.js"),
      { encoding: "utf-8" }
    );
    jsFile = jsFile.replace(reg, projectName);
    try {
      let tempDir = fs.statSync(path.resolve(res.programDir, `${projectName}`));
      if (!tempDir.isDirectory()) {
        fs.mkdirSync(path.resolve(res.programDir, `${projectName}`));
      }
    } catch (error) {
      fs.mkdirSync(path.resolve(res.programDir, `${projectName}`));
    }
    fs.writeFileSync(
      path.resolve(res.programDir, `${projectName}`, `index.vue`),
      `${vueComponent}${jsComponent}${cssComponent}`
    );
    fs.writeFileSync(
      path.resolve(res.programDir, `${projectName}`, `index.js`),
      `${jsFile}`
    );
    // 执行脚本程序，并输出执行内容
    execa("npm", ["run", "build"]).stdout.pipe(process.stdout);
  });
};
